package
{
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import spark.components.Label;

	/**
	 * 游侠，数据表打包成1个文件
	 */
	public class JsonZip
	{
		private static var _ins:JsonZip;
		
		public var printMsg:Label;
		public var importRoot:String;
		public var exportUrl:String;
		
		private var _loadList:Array = [];//需要加载的文件列表
		private var _contentList:Array = [];//已经加载好的 文本内容列表
		private var _count:int = 0;
		private var _maxCount:int = 0;
		private var _cfgStream:FileStream;
		
		private var _outObjArr:Array;
		
//		private var _timer:Timer;
		
		private static var SELECTEID:int = 20;//全局UI文件的ID
		private var _posX:int = 0;//匹配LAYAUI的第一个“x”
		private var _compId:int = 1;
		
		public static function get ins():JsonZip
		{
			if(!_ins){
				_ins = new JsonZip();
			}
			return _ins;
		}
		public function get running():Boolean
		{
			return Boolean(_loadList.length > 0);
		}
		
		public function JsonZip()
		{
			_cfgStream = new FileStream();
			
//			_timer = new Timer(100);
//			_timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		/**
		 * 设置文件列表
		 */
		public function setList(list:Array):void
		{
			_loadList = list;	
			_maxCount = list.length;
			_count = 0;
		}
		/**
		 * 启动开始加载，需先调用 setList
		 */
		public function startLoad():void
		{
			_contentList.length = 0;
			nextLoad();
		}
		private function nextLoad():void
		{
			if(_loadList.length)
			{
				var url:String = _loadList.shift();
				var loader:TextLoader = new TextLoader();
				loader.url = url;
				loader.dataFormat = URLLoaderDataFormat.TEXT;
				loader.addEventListener(Event.COMPLETE, handleComplate);
				loader.addEventListener(IOErrorEvent.IO_ERROR, handleComplate);
				loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
				loader.load(new URLRequest(url));
			}
			else
			{
				_count = 0;
				_maxCount = _contentList.length;
				
//				//开始输出新文件
//				if(!_timer.running)
//				{
//					_timer.start();
//				}
				outHandler();
			}
		}
		private function handleComplate(e:Event):void
		{
			trace("UI-加载成功！");
			var loader:TextLoader = e.target as TextLoader;
			loader.removeEventListener(Event.COMPLETE, handleComplate);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, handleComplate);
			loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
			
			_contentList.push(loader);
			
			_count ++;
			var fix:String = "正在加载：";
			if(_count >= _maxCount){
				fix = "压缩完成：";
				NativeApplication.nativeApplication.exit();
			}
			printMsg.text = fix + _count + "/" + _maxCount + "   url=" + loader.url;
			
			nextLoad();
		}
		private function handleHttpStatus(e:Event):void
		{
			trace("UI-404错误！");
		}
//		private function onTimer(e:TimerEvent):void
//		{
//			if(_contentList.length)
//			{
//				var loader:TextLoader = _contentList.shift();
//				writeLayaUI(loader);
//			}
//			else
//			{
//				_timer.stop();
//			}
//		}
		private function outHandler():void
		{
			var content:String = "";
			for(var i:int=0; i<_contentList.length; i++){
				var loader:TextLoader = _contentList[i];
				content += writeLayaUI(loader);
			}
			
//			var path:String = "json.gif";
			var path:String = "json.css";
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(path);
			try
			{
				//压缩二进制
//				var bt:ByteArray = new ByteArray();
//				bt.writeUTFBytes(content);
//				bt.compress("zlib");
//				
//				_cfgStream.open(fl, FileMode.WRITE);
//				
//				_cfgStream.writeBytes(bt);
//				_cfgStream.close();
				
				//不压缩，纯字符串
				_cfgStream.open(fl, FileMode.WRITE);
				
				_cfgStream.writeUTFBytes(content);
				_cfgStream.close();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
		}
		public function writeLayaUI(loader:TextLoader):String
		{
			SELECTEID ++;
			
			var path:String;
			var txtStr:String;
			var hz:String;
			var url:String = loader.url;
			
			var startIndex:int = url.lastIndexOf("/");
			var endIndex:int = url.length;
			var dic2:String = url.substring(startIndex+1, endIndex);
			var dicStart:int = importRoot.lastIndexOf("/");
			var dicEnd:int = startIndex;
			var dic:String = url.substring(dicStart+1, dicEnd);
			if(dic == "")
			{
				path = dic + dic2;
			}
			else
			{
				path = dic + "/" + dic2;
			}
			
			var content:String = dic2 + "$neibufenge$" + loader.data + "$wenjianfenge$";
			
			return content;
		}
		private function toJs(key:String):String
		{
			return key;
			//			return "\"" + key + "\"";
		}
		private function jsStr(key:String, value:*, isInt:Boolean = false):String
		{
			//			return key + ":" + value;
			if(isInt){
				return "\"" + key + "\":" + value;
			}
			else{
				return "\"" + key + "\":\"" + value + "\"";
			}
		}
	}
}

import flash.net.URLLoader;

class TextLoader extends URLLoader
{
	public var url:String;
	
	public function TextLoader()
	{
		super();
	}
}